package com.mijie.homi.ns.traffic.receptor;

import java.util.Date;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.homi.common.constant.TypeCode;
import com.mijie.homi.common.domain.Notify;
import com.mijie.homi.common.domain.PushMessage;
import com.mijie.homi.common.domain.user.UserExtInfo;
import com.mijie.homi.common.protocol.HomiProtocol;
import com.mijie.homi.common.util.HomiUtil;
import com.mijie.homi.ns.core.HomiServer;
import com.mijie.homi.ns.domain.Constants;
import com.mijie.homi.ns.service.NotifyService;
import com.mijie.homi.ns.service.UserService;
import com.mijie.util.Helper;

@Service
public class SystemMessageReceptor implements Receptor{

	@Autowired
	private NotifyService notifyService;
	@Autowired
	private UserService userService;
	@Autowired
	private HomiServer homiServer;
	
	@Override
	public boolean accept(short type) {
		return type==TypeCode.MESSAGE_ROUTER_TYPE_SYSTEM_MESSAGE;
	}
	
	@Override
	public void process(int receiver,short type,JSONObject originalPack){
		if(type>0){
			
			originalPack.accumulate("notifyId", "sys_msg_" + originalPack.getInt("id"));
			originalPack.put("createAt", new Date().getTime());
			HomiProtocol pushProtocol = new HomiProtocol(type);
			pushProtocol.setContent(originalPack.toString());
			
			Map<Long,IoSession> sessionMap = homiServer.getManagedSessions();
			IoSession session = null;
			for(Long key : sessionMap.keySet()){
				session = sessionMap.get(key);
				if(session!=null){
					session.write(pushProtocol);
				}
			}
			
				/*if(receiverSession!=null){
					HomiServer.INFO("socket push solicited message type->"+type+",content->"+originalPack.toString());
					receiverSession.write(pushProtocol);
				}else{
					HomiServer.INFO("offline push solicited message type->"+type+",content->"+originalPack.toString());
					UserExtInfo extInfo = userService.getUserExtInfoByUserId(receiver);
					if(HomiUtil.doOfflinePush(notify.getType()) && extInfo!=null && extInfo.getOs().equalsIgnoreCase("ios")){
						PushMessage pushMsg = new PushMessage();
						pushMsg.setContent(notify.getContent());
						pushMsg.setId(Helper.genUUID());
						pushMsg.setContentType(notify.getType());
						pushMsg.setReceiver(receiver);
						notifyService.addToPushQueue(pushMsg);
					}
				}*/
			
		}
	}
}
